package com.tangsm.spring.boot.deferred.result.controller;

import com.tangsm.spring.boot.deferred.result.domain.vo.Result;
import com.tangsm.spring.boot.deferred.result.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;

/**
 * Callable异步请求调用
 *
 * @author tangsm
 */
@RestController
@RequestMapping("/task")
public class CallableTaskController {
    private static final Logger log = LoggerFactory.getLogger(CallableTaskController.class);

    @Autowired
    private TaskService taskService;

    /**
     * Callable异步请求
     * <pre>
     * 当controller返回值是Callable的时候，springmvc就会启动一个线程将Callable交给TaskExecutor去处理
     * 然后DispatcherServlet还有所有的spring拦截器都退出主线程，然后把response保持打开的状态
     * 当Callable执行结束之后，springmvc就会重新启动分配一个request请求，然后DispatcherServlet就重新
     * 调用和处理Callable异步执行的返回结果， 然后返回视图
     * </pre>
     *
     * @return 响应结果
     */
    @GetMapping(value = "/get")
    public Callable<Result<String>> getResult() {
        log.info("接收请求，开始处理...");

        Callable<Result<String>> result = (() -> taskService.getResult());

        log.info("接收任务线程完成并退出");
        return result;
    }
}
